<template>
  <div>
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{this.$router.currentRoute.name}}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-page-header @back="goBack" :content="this.$router.currentRoute.name.substring(this.$router.currentRoute.name.indexOf('/')+1)">
      </el-page-header>
    <!-- 系统通知列表卡片区 -->
      <el-form :inline="true" ref="form" :model="queryMap"  size="small" style="margin-top: 2vh">
        <el-row>
          <h4 style="margin: 1vh 0 2vh;color: #1f2d3d">条件查询区</h4>
        </el-row>
        <el-form-item>
          <el-select
              style="width: 140px;"
              placeholder="请选择账号"
              v-model="queryMap.accountName"
              @change="getUserNickName"
              filterable
          >
            <el-option
                v-for="(name) in accountName"
                :key="name"
                :label="name"
                :value="name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryMap.nickNameId" style="width: 140px;" filterable placeholder="请选择坐席昵称">
            <el-option
                v-for="(user) in userList"
                :key="user.userId"
                :label="user.userName+'('+user.nickName+')'"
                :value="user.userId">
            </el-option>
          </el-select>
        </el-form-item>

<!--        <el-form-item>-->
<!--          <el-select v-model="queryMap.deptNameId" style="width: 140px;" filterable placeholder="请选择部门">-->
<!--            <el-option-->
<!--                v-for="department in departments"-->
<!--                :label="department.deptName"-->
<!--                :key="department.deptId"-->
<!--                :value="department.deptId">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="结束时间:">
          <el-date-picker
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              @change="handleDateChange"
              v-model="value2">
          </el-date-picker>
        </el-form-item>
        <el-form-item >
            <el-button @click="reset" icon="el-icon-refresh">重置</el-button>
            <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
        </el-form-item>
      </el-form>

      <div style="margin-bottom: 10px;display: flex">
        <span class="hint" style="flex: 1;font-size: 11px;line-height: 5vh">温馨提示：查询时，必须带时间，如没有则默认今天</span>
        <el-button style="" @click="downExcelBatch" v-hasPermission="'seatTraffic:downExcelBotch'" icon="el-icon-download">批量导出</el-button>
        <el-button style=""  @click="downExcel" v-hasPermission="'seatTraffic:downExcelAll'" icon="el-icon-download">全部导出</el-button>
      </div>
      <!-- 表格区域 -->
      <el-table ref="multipleTable"  size="small" :data="seatTraffics" @selection-change="handleSelectionChange"
                border style="width: 100%;" height="420">
        <el-table-column type="selection" width="40"></el-table-column>
        <el-table-column prop="nickName" label="坐席昵称" width="100"></el-table-column>
        <el-table-column prop="userName" label="用户名" width="100"></el-table-column>
        <el-table-column prop="deptName" label="部门名称" width="100"></el-table-column>
        <el-table-column label="通话数" width="60">
          <template v-slot="scope">
            {{(scope.row.callNum==null?0:scope.row.callNum)}}
          </template>
        </el-table-column>
        <el-table-column label="通话成功数" width="90">
          <template v-slot="scope">
            {{(scope.row.callSuccess==null?0:scope.row.callSuccess)}}
          </template>
        </el-table-column>
        <el-table-column label="成功率" width="90">
          <template v-slot="scope">
            {{ (scope.row.callSuccessRate == null ? "0.00%" : scope.row.callSuccessRate)}}
          </template>
        </el-table-column>
        <el-table-column label="平均通话时长" width="100">
          <template v-slot="scope">
            {{(scope.row.callAverageDuration==null?0:formatTime(scope.row.callAverageDuration))}}
          </template>
        </el-table-column>
        <el-table-column label="通话总时长" width="100">
          <template v-slot="scope">
            {{(scope.row.callTotalDuration==null?0:formatTime(scope.row.callTotalDuration))}}
          </template>
        </el-table-column>
        <el-table-column label="计费时长" width="100">
          <template v-slot="scope">
            {{(scope.row.billingDuration==null?0:scope.row.billingDuration)}}分钟
          </template>
        </el-table-column>
        <el-table-column label="呼出数" width="60">
          <template v-slot="scope">
            {{(scope.row.exhaleNum==null?0:scope.row.exhaleNum)}}
          </template>
        </el-table-column>
        <el-table-column label="中砖号码呼出成功数" width="90">
          <template v-slot="scope">
            {{(scope.row.exhaleSuccess==null?0:scope.row.exhaleSuccess)}}
          </template>
        </el-table-column>
        <el-table-column label="呼出成功率" width="100">
          <template v-slot="scope">
            {{(scope.row.exhaleSuccessRate==null?"0.00%":scope.row.exhaleSuccessRate)}}
          </template>
        </el-table-column>
        <el-table-column label="呼出平均通话时长" width="120">
          <template v-slot="scope">
            {{(scope.row.exhaleAverageDuration==null?0:formatTime(scope.row.exhaleAverageDuration))}}
          </template>
        </el-table-column>
        <el-table-column label="呼出通话总时长" width="110">
          <template v-slot="scope">
            {{(scope.row.exhaleTotalDuration==null?0:formatTime(scope.row.exhaleTotalDuration))}}秒
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          style="margin-top:10px;"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryMap.pageNum"
          :page-sizes="this.$globalVar.sizes"
          :page-size="queryMap.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>

    </el-card>
  </div>
</template>
<script>
import axios from "axios";
import {format} from "echarts/lib/export";

export default {
  data() {
    return {
      loading: true,
      total: 0,
      multipleSelection:[],
      seatTraffics:[],

      accountName:[],//账号
      userList:[],//用户昵称
      departments:[],//部门名称
      value2: [new Date(),new Date()],//日期选择器
      //查询对象
      queryMap: {
        userIds:[],//批量导出的用户ID
        pageNum: 1,
        pageSize: 10,
        nickNameId: '',
        //deptNameId:"",
        startTime:null,
        deadline:null,
        accountName:'',
      },
        pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      durationOptions:{
        0:"1秒",
        1:"20秒",
        2:"30秒",
        3:"40秒",
        4:"50秒",
        5:"60秒",
        6:"70秒",
        7:"80秒",
        8:"90秒",
        9:"100秒",
        10:"110秒",
        11:"120秒",
        12:"120秒以上",
      }
    };
  },
  methods: {
    format(num,style){
      return  format(num,style);
    },
    formatTime(seconds) {
      if (seconds == null) {
        return "0分0秒";
      }
      const minutes = Math.floor(seconds / 60); // 计算分钟数
      const remainingSeconds = seconds % 60; // 计算剩余秒数
      return `${minutes}分${remainingSeconds}秒`;
    },
    /**
     * 重置
     */
    reset(){
      this.value2=[new Date(),new Date()];//日期选择器
      this.queryMap= {
        userIds:[],//批量导出的用户ID
        pageNum: 1,
        pageSize: 10,
        nickNameId: "",
        //deptNameId:"",
        startTime:this.formatDate(this.value2[0],false),
        deadline:this.formatDate(this.value2[1],true),
        accountName:'',
      };
      this.getUserNickName();
    },
    /**
     * 全选功能
     *
     */
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    /**
     *  改变页码
     */
    handleSizeChange(newSize) {
      this.queryMap.pageSize = newSize;
      this.getSeatTraffics();
    },
    /**
     * 翻页
     */
    handleCurrentChange(current) {
      this.queryMap.pageNum = current;
      this.getSeatTraffics();
    },
    /**
     * 当时间选择时，直接赋值
     */
    handleDateChange() {
      this.queryMap.startTime=this.formatDate(this.value2[0],false);
      this.queryMap.deadline=this.formatDate(this.value2[1],true);
    },
    /**
     * 获得用户昵称信息
     */
    async getUserNickName(){
      this.queryMap.nickNameId="";
      const {data: res} = await this.$http.post("/system/departmentUtils/getUserListByMap/",this.queryMap);
      if(!res.success){
        return this.$message.error("获取用户昵称信息失败:"+res.data.errorMsg);
      }
      this.userList=res.data
    },
    /**
     * 获得账号信息
     */
    async getAccountNameList() {
      const {data: res} = await this.$http.get("/system/user/qt/findRoleList");
      if (!res.success) {
        return this.$message.error("获取角色信息失败:" + res.data.errorMsg);
      }
      this.accountName = res.data

    },
    /**
     * 根据当前登录用户获得当前部门及所有下级部门
     */
    async getDepartmets() {
      const { data: res } = await this.$http.get("system/dept/findDept/");
      if(!res.success){
        return this.$message.error("获取部门列表失败:"+res.data.errorMsg);
      }
      //this.data = res.data.tree;
      this.departments = res.data;
    },


    search(){
      this.queryMap.pageNum = 1;
      this.getSeatTraffics();
    },
    //得到坐席话务统计列表
    async getSeatTraffics(){
      if (this.value2==null ){
        this.value2=[new Date(),new Date()];//日期选择器
      }
      const { data: res } = await this.$http.get("/system/callLog/findListSeatTraffic",{
        params: this.queryMap
      }
      );
      if(!res.success){
        return this.$message.error("获取坐席话务统计列表失败:"+res.data.errorMsg);
      }
      this.total = res.data.total;
      this.seatTraffics=res.data.rows;
    },
    /**
     * 批量导出坐席话务统计表格
     */
    downExcelBatch() {
      if (this.total > 0) {
        if (this.multipleSelection.length==0){
          this.$message('未选择资源');
          return;
        }
        //获取选中的资源id
        const ids = this.multipleSelection.map(row => row.userId);
        this.queryMap.userIds=ids
        console.log(ids)
        const $this = this;
        const res = axios.post(
            'http://47.99.186.44:8990/system/callLog/seatTrafficDownExcelBatch',
            this.queryMap,
            // 这里需要注意，queryMap 如果是用于请求体，就直接作为第二个参数传入
            {
              responseType: 'blob',
              headers: {
                'Authorization': LocalStorage.get(LOCAL_KEY_XINGUAN_ACCESS_TOKEN)
              }
            }
        )
            .then(res => {
              if (res.headers["content-type"] === "application/json") {
                return $this.$message.error(
                    "Subject does not have permission [task:export]"
                );
              }
              const data = res.data;
              let url = window.URL.createObjectURL(data); // 将二进制文件转化为可访问的url
              const a = document.createElement("a");
              document.body.appendChild(a);
              a.href = url;
              a.download = "坐席话务统计列表.xls";
              a.click();
              window.URL.revokeObjectURL(url);
            });
      }else {
        this.$message({
          title:'操作失败',
          message:"没有任何数据可导出",
        });
        this.queryMap.userIds=[];
        console.log(this.queryMap)
      }
    },

    /**
     * 加载坐席话务统计表格的前置条件
     */
    async downExcel() {
      if (this.total > 0) {
        const res = await this.$confirm(
            "此操作将会把查询出的所有坐席话务记录导出, 是否继续?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }
        ).catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
        if (res === "confirm") {
          this.downExcelAll()
        }
      }else {
        this.$message({
          title:'操作失败',
          message:"没有任何数据可导出",
        });
      }
    },
    /**
     * 加载坐席话务统计表格
     */
    downExcelAll(){
      const $this = this;
      const res = axios.post(
          'http://47.99.186.44:8990/system/callLog/seatTrafficDownExcelAll',
          this.queryMap, // 这里需要注意，queryMap 如果是用于请求体，就直接作为第二个参数传入
          {
            responseType: 'blob',
            headers: {
              'Authorization': LocalStorage.get(LOCAL_KEY_XINGUAN_ACCESS_TOKEN)
            }
          }
      )
          .then(res => {
            console.log(res)
            if (res.headers["content-type"] === "application/json") {
              return $this.$message.error(
                  "Subject does not have permission [task:export]"
              );
            }
            const data = res.data;
            let url = window.URL.createObjectURL(data); // 将二进制文件转化为可访问的url
            const a = document.createElement("a");
            document.body.appendChild(a);
            a.href = url;
            a.download = "坐席话务统计列表（按条件）.xls";
            a.click();
            window.URL.revokeObjectURL(url);
          })
    },

    // 定义一个格式化时间的函数
    formatDate(date,is) {
      //判断时间是否为空
      if (date != null) {
        //判断是否为结束时间
        if (is) {
          date.setDate(date.getDate() + 1);
        }
        const year = date.getFullYear();
        //+1，是因为月份是从0开始
        const month = ('0' + (date.getMonth() + 1)).slice(-2);
        const day = ('0' + date.getDate()).slice(-2);
        // // console.log('格式化前各部分值: 年:', year,'月:', month,'日:', day);
        // const hours = ('0' + date.getHours()).slice(-2);
        // const minutes = ('0' + date.getMinutes()).slice(-2);
        // const seconds = ('0' + date.getSeconds()).slice(-2);
        return `${year}-${month}-${day} 00:00:00`;
        // console.log('最终返回结果:', result);
      }
      return null;
    },
  },
  created() {
    this.handleDateChange();
    this.getUserNickName();
    //this.getDepartmets();
    this.getSeatTraffics();
    this.getAccountNameList();
  },
  mounted() {
  },
};
</script>

<style scoped>
.hint{
  margin-left: 2vh;font-weight: 400;font-size: 12px;color: red;
}
</style>